<script lang="ts" setup>
import { ref } from 'vue'
import { changePassword } from '@/services/api'
import { useUserStore } from '@/state/modules/user'
import { HideLoading, Loading, Toast } from '@/utils/uniapi/prompt'
import tmForm from '@/tmui/components/tm-form/tm-form.vue'
import { useRouter } from '@/hooks/router'

const userStore = useUserStore()
const entity = ref<ApiModels.base.ChangePasswordModel>({
  userName: userStore.userInfo.userName,
  password: '',
  newPassword: '',
  confirmPassword: '',
})

const form = ref<InstanceType<typeof tmForm> | null>(null)
const router = useRouter()
const submitHandle = async (e: any) => {
  console.log(e)
  if (!e?.isPass) {
    Toast('请检查表单内容是否完整', { mask: false, position: 'bottom' })
    return
  }
  Loading('loading...')
  const { error } = await changePassword(entity.value)
  HideLoading()
  if (error) {
    Toast(error.msg, { icon: 'error' })
    return
  }
  Toast('修改成功', { icon: 'success' })
  setTimeout(() => router.back(), 1000)
}
</script>

<template>
  <tm-app>
    <tm-form ref="form" v-model="entity" :margin="[0]" :label-width="190" @submit="submitHandle">
      <tm-form-item label="账号" :margin="[0]" field="userName">
        <tm-input
          v-model.lazy="entity.userName"
          :input-padding="[0, 0]"
          :transprent="true"
          disabled
        />
      </tm-form-item>

      <tm-form-item required label="旧密码" :margin="[0]" field="password" :rules="[{ required: true, message: '必填' }]">
        <tm-input
          v-model.lazy="entity.password"
          :input-padding="[0, 0]"
          :transprent="true"
          password
        />
      </tm-form-item>

      <tm-form-item
        required label="新密码" :margin="[0]" field="newPassword" :rules="[{ required: true, message: '必填' }]"
      >
        <tm-input
          v-model.lazy="entity.newPassword"
          :input-padding="[0, 0]"
          :transprent="true"
          password
        />
      </tm-form-item>

      <tm-form-item
        required label="确认密码" :margin="[0]" field="confirmPassword" :rules="[
          { required: true, message: '必填' },
          {
            message: '两次输入密码不一致',
            validator: (val:string) => val === entity.newPassword,
          }]"
      >
        <tm-input
          v-model.lazy="entity.confirmPassword"
          :input-padding="[0, 0]"
          :transprent="true"
          password
        />
      </tm-form-item>
    </tm-form>

    <tm-sheet :margin="[0]" :transprent="true">
      <tm-button label="保存" block @click="form?.submit()" />
    </tm-sheet>
  </tm-app>
</template>

<style lang="scss" scoped></style>
